<?php
namespace app\controller\api;

use app\BaseController;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

require root_path() . 'vendor/qiniu/autoload.php';

class Upload extends BaseController
{
    public function uploadImage()
    {
        // thinkphp 接收文件
        $file = $this->request->file('image');
        // 临时文件
        $tmp_name = $file->getPathname();
        // 原始文件的后缀名
        $ext = $file->getOriginalExtension();
        // 重新命名
        $newName = uniqid() . time() . '.' . $ext;
        $auth = new Auth(config('zmt.qiniu.accessKey'), config('zmt.qiniu.secretKey'));
        $uploadToken = $auth->uploadToken(config('zmt.qiniu.bucket'));
        $uploadManager = new UploadManager();
        list($ret, $err) = $uploadManager->putFile($uploadToken, $newName, $tmp_name);
        if ($err !== null) {
            $this->error($err);
        } else {
            $this->success('上传成功', [
                'url' => 'http://rvuw3qq9y.hd-bkt.clouddn.com/' . $ret['key']
            ]);
        }
    }
}
